package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    // 线程池
    private final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(5);


    @Override
    public Result queryById(Long id) {
//        Shop shop = getShop(id);
//        Shop shop = queryWithPassThrough(id);
        Shop shop = queryWithMutex(id);
//        Shop shop = queryWithLogicalExpire(id);
        if (shop == null) {
            return Result.fail("该店铺不存在");
        }
        return Result.ok(shop);
    }

    /**
     * 利用逻辑过期解决缓存击穿
     *
     * @param id
     * @return
     */
    private Shop queryWithLogicalExpire(Long id) {
        String key = "cache:shop:" + id;
        String jsonStr = redisTemplate.opsForValue().get(key);

        if (StrUtil.isBlank(jsonStr)) {
            return null;
        }

        // jsonStr 不为空，人为的通过代码去判断有没有过期
        RedisData redisData = JSONUtil.toBean(jsonStr, RedisData.class);
        JSONObject jsonObject = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(jsonObject, Shop.class);
        if (LocalDateTime.now().isBefore(redisData.getExpireTime())) {
            log.info("缓存没有过期，直接返回");
            return shop;
        }

        // 缓存过期了，需要进行缓存的重建
        String lockKey = "lock:shop:" + id;
        boolean lock = tryLock(lockKey);
        if (lock) {
            log.info("没有拿到互斥锁，直接返回过期的旧数据");
            return shop;
        }

        log.info("拿到互斥锁了，让一个新的线程去进行缓存的重建，本线程直接返回过期的旧数据");
        CACHE_REBUILD_EXECUTOR.submit(() -> {
            try {
                saveHotShopToRedis(id);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unlock(lockKey);
            }
        });

        log.info("让一个新的线程去进行缓存的重建，本线程直接返回过期的旧数据");
        return shop;
    }

    public void saveHotShopToRedis(Long id) {
        String key = "cache:shop:" + id;
        RedisData redisData = new RedisData();
        redisData.setData(getById(id));
        // 10s就过期，方便测试代码
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(10));
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 利用互斥锁解决缓存击穿
     *
     * @param id
     * @return
     */
    private Shop queryWithMutex(Long id) {

        String key = "cache:shop:" + id;
        String jsonStr = redisTemplate.opsForValue().get(key);

        if (StrUtil.isNotBlank(jsonStr)) {
            return JSONUtil.toBean(jsonStr, Shop.class);

        }

        if ("".equals(jsonStr)) {
            return null;
        }

        // 重建缓存，只让一个线程去做就行了
        String lockKey = "lock:shop" + id;
        Shop shop = null;

        try {
            boolean lock = tryLock(lockKey);
            if (lock) {
                // Double Check
                if (StrUtil.isNotBlank(jsonStr)) {
                    shop = JSONUtil.toBean(jsonStr, Shop.class);
                    return shop;
                }
                log.info("拿到互斥锁，开始重建缓存");
                shop = getById(id);
                if (shop == null) {
                    log.info("店铺不存在，缓存空对象");
                    redisTemplate.opsForValue().set(key, "", 30, TimeUnit.MINUTES);
                    return null;
                }

                // 模拟重建缓存的延时
                Thread.sleep(200);
                log.info("将店铺id：{}，放入缓存中", id);
                redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), 5, TimeUnit.MINUTES);

                return shop;
            }

            // 没有拿到互斥锁
            Thread.sleep(50);
            return queryWithMutex(id);
        } catch (InterruptedException e) {
            throw new RuntimeException();
        } finally {
            unlock(lockKey);
        }

    }

    private boolean tryLock(String key) {
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    private void unlock(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 解决缓存穿透
     *
     * @param id
     * @return
     */
    private Shop queryWithPassThrough(Long id) {
        Shop shop = null;

        String key = "cache:shop:" + id;
        String jsonStr = redisTemplate.opsForValue().get(key);

        if (StrUtil.isNotBlank(jsonStr)) {
            shop = JSONUtil.toBean(jsonStr, Shop.class);
            return shop;
        }

        if ("".equals(jsonStr)) {
            return null;
        }

        shop = getById(id);
        if (shop == null) {
            log.info("店铺不存在，缓存空对象");
            redisTemplate.opsForValue().set(key, "", 2, TimeUnit.MINUTES);
            return null;
        }

        log.info("将店铺id：{}，放入缓存中", id);
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), 5, TimeUnit.MINUTES);
        return shop;
    }

    /**
     * 最开始的基础版本
     *
     * @param id
     * @return
     */
    private Shop getShop(Long id) {
        String key = "cache:shop:" + id;
        String jsonStr = redisTemplate.opsForValue().get(key);
        Shop shop = null;
        if (jsonStr == null || jsonStr == "") {
            shop = getById(id);
            if (shop == null) {
                return null;
            }
            // 放入缓存中
            log.info("将店铺id：{}，放入缓存中", id);
            redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), 5, TimeUnit.MINUTES);
        } else {
            log.info("店铺id：{}，存在缓存中，直接返回，无需查询MySQL数据库", id);
            shop = JSONUtil.toBean(jsonStr, Shop.class);
        }
        return shop;
    }
}
